package com.yydm.servicesms.controller;

import com.yydm.commonutils.R;
import com.yydm.servicesms.service.SmsService;
import com.yydm.servicesms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Classname SmsController
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/7/8 10:51
 * @Created by liu25
 */
@RestController
@RequestMapping("/servicesms/sms")
//@CrossOrigin  //跨域
public class SmsController {

    @Autowired
    private SmsService service;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public R sendSms(@PathVariable String phone) {
//        从redis中直接获取验证码,如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
//        生成随机值,传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
//        调用service发送短信的方法
        Boolean isSend = service.send(map, phone);
        if (isSend) {
//            发送成功把发送成功的验证码发到redis里面
//            设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }

    }


}
